<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Requests\System\DictItem\StoreRequest;
use App\Http\Requests\System\DictItem\UpdateRequest;
use App\Http\Resources\System\DictItem\IndexResource;
use App\Http\Resources\System\DictItem\InfoResource;
use App\Models\System\DictItem;
use Illuminate\Http\JsonResponse;
use Spatie\QueryBuilder\QueryBuilder;

class DictItemController extends Controller
{
    public function index(): JsonResponse
    {
        $query = DictItem::query();
        $list = QueryBuilder::for($query)
            ->allowedFilters(['title', 'code'])
            ->get();

        return $this->success(IndexResource::collection($list));
    }

    public function show(DictItem $dict): JsonResponse
    {
        return $this->success(new InfoResource($dict));
    }

    public function store(StoreRequest $request): JsonResponse
    {
        $data = $request->validated();
        $row = new DictItem($data);
        $row->save();

        return $this->success([], '添加成功');
    }

    public function update(DictItem $dict, UpdateRequest $request): JsonResponse
    {
        $data = $request->validated();
        $dict->fill($data);
        $dict->save();

        return $this->success([], '更新成功');
    }

    public function destroy(DictItem $dict): JsonResponse
    {
        $dict->delete();

        return $this->success([], '删除成功');
    }
}
